# coding=utf-8
from flask import g
from flask_restful import Resource
from flask_restful.reqparse import RequestParser
from comment.ultils.decorators import Login_required
from comment.modules.user import User
from comment.modules.bank_card import BankCard
from comment.modules import db
from financial.resorces.card.serializer import BankCardListSerializer

class Card_Resource(Resource):

    method_decorators = [Login_required]  # 使用了登录拦截的装饰器

    '''
    银行卡管理的资源类
    '''

    def post(self):
        uid = g.user_id
        login_user = User.query.filter(User.id == uid).first()

        '''
        添加银行卡
        :return:
        '''
        rp = RequestParser()
        rp.add_argument('holder', required=True) #持卡人，账号的名字
        rp.add_argument('openingBank', required=True)  # 开户银行
        rp.add_argument('bankBranch', required=True)  # 支行
        rp.add_argument('cityId', required=True)  # 城市id
        rp.add_argument('cardNum', required=True)  # 卡片号码

        args = rp.parse_args()

        holder = args.holder
        opening_bank = args.openingBank
        bank_branch = args.bankBranch
        city_id = args.cityId
        bank_card_num = args.cardNum

        '''验证银行卡卡号是否唯一'''
        card_info = BankCard.query.filter(BankCard.bankCardNum == bank_card_num).first()
        if card_info:
            return {
                'message':'银行卡已经存在，请勿重复添加',
                'code':209
            }
        #把银行卡数据保存到数据库中
        card = BankCard(bankCardNum=bank_card_num,
                        openingBank=opening_bank,
                        bankBranch=bank_branch,
                        cityId=city_id,
                        holder=holder,
                        userId=uid,
                        reservePhone=login_user.phone
                        )
        db.session.add(card)
        db.session.commit()

        return {'msg':'success'}

    def get(self):
        '''
        查询当前登录用户所拥有的银行卡列表
        :return:
        '''

        uid = g.user_id

        #查询数据库中，当前用户下所有的银行卡
        card_list = BankCard.query.filter(BankCard.userId == uid).all()
        if card_list: #把对象转化成字典数据
            return BankCardListSerializer(card_list).to_dict()
        else:
            return {}
    #删除银行卡
    def delete(self):
        rp = RequestParser()
        rp.add_argument('cardNum', required=True)

        args = rp.parse_args()
        bankCardNum = args.cardNum

        cardInfo = BankCard.query.filter(BankCard.bankCardNum == bankCardNum)
        if cardInfo:
            cardInfo.delete()
            db.session.commit()
            return {'msg': 'success'}
        else:
            return {"code": 20008, 'message': '没有这个银行卡'}















